package il.ac.tau.cg.ex5.obj;

import il.ac.tau.cg.ex5.util.Face;
import il.ac.tau.cg.ex5.util.Vertex;

public class ObjEntity
{
	private Face[] faces;
	
	private Vertex min;
	private Vertex max;
	
	public ObjEntity(Face[] faces)
	{
		this.faces = faces;
		
		calculateMinMax();
	}
	
	public Face[] getFaces()
	{
		return faces;
	}
	
	public Vertex getMin()
	{
		return min;
	}
	
	public Vertex getMax()
	{
		return max;
	}
	
	private void calculateMinMax()
	{
		float minX = Float.MAX_VALUE;
		float minY = Float.MAX_VALUE;
		float minZ = Float.MAX_VALUE;
		
		float maxX = Float.MIN_VALUE;
		float maxY = Float.MIN_VALUE;
		float maxZ = Float.MIN_VALUE;
		
		for (Face face : faces)
		{
			for (Vertex vertex : face.vertices)
			{
				minX = Math.min(minX, vertex.x);
				minY = Math.min(minY, vertex.y);
				minZ = Math.min(minZ, vertex.z);
				
				maxX = Math.max(maxX, vertex.x);
				maxY = Math.max(maxY, vertex.y);
				maxZ = Math.max(maxZ, vertex.z);
			}
		}
		
		min = new Vertex(minX, minY, minZ);
		max = new Vertex(maxX, maxY, maxZ);
	}
	
	public float calculateIdentityScale()
	{
		float spanX = max.x - min.x;
		float spanY = max.y - min.y;
		float spanZ = max.z - min.z;
		
		return 1.0f / Math.max(Math.max(spanX, spanY), spanZ);
	}
	
	public Vertex calculateCenterMass()
	{
		double totalX = 0.0;
		double totalY = 0.0;
		double totalZ = 0.0;
		
		int vertexCount = 0;
		
		for (Face face : faces)
		{
			for (Vertex vertex : face.vertices)
			{
				totalX += vertex.x;
				totalY += vertex.y;
				totalZ += vertex.z;
				
				vertexCount++;
			}
		}
		
		float x = (float)(totalX / vertexCount);
		float y = (float)(totalY / vertexCount);
		float z = (float)(totalZ / vertexCount);
		
		return new Vertex(x, y, z);
	}
}
